import Vue from 'vue'
import Vuex from 'vuex'

import {
	auth,
	getUserInfo,
	logout
} from "@/api/user";

import {
	TOKEN,
	REFRESH_TOKEN,
	USER_INFO,
	TENANT_ID,
	SHOP_ID,
	QQMAP_KEY
} from '@/config/const';

const QQMapWX = require('@/libs/qqmap-wx-jssdk.min.js');
Vue.use(Vuex)

/**
 * 获取服务供应商
 */
function getProvider() {
	return new Promise((resolve, reject) => {
		uni.getProvider({
			service: 'oauth',
			success(res) {
				resolve(res.provider);
			},
			fail() {
				resolve(false);
			}
		});
	});
}

const store = new Vuex.Store({
	state: {
		userInfo: {},
		token: false,
		refreshToken: false,
		currentLocation: {
			localCity: '太原市',
			longitude: 112.566831,
			latitude: 37.866003,
			isDefault: true
		},
		qqmapsdk: false,
		currentStoreId: '',
		curretnStore: {}
	},
	mutations: {
		setToken(state, token) {
			state.token = token;
		},
		setRefreshToken(state, refreshToken) {
			state.refreshToken = refreshToken;
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
		},
		setCurrentLocation(state, loc) {
			state.currentLocation = loc
		},
		setCurrentStoreId(state, id) {
			state.currentStoreId = id
		},
		setCurrentStore(state, currStore) {
			state.curretnStore = currStore
		}
	},
	getters: {
		isLogin: state => {
			return (!state.token || state.token === '') ? false : true
		},
		userInfo: state => state.userInfo,
		token: state => state.token,
		currentLocation: state => state.currentLocation,
		currentStoreId: state => state.currentStoreId,
		curretnStore: state => state.curretnStore
	},
	actions: {
		getCode: function() {
			return new Promise((resolve, reject) => {
				let provider = getProvider();
				uni.login({
					provider: provider,
					success(res) {
						return resolve(res.code);
					},
					fail() {
						return reject(null);
					}
				})
			})
		},
		/**
		 * 小程序登录
		 */
		loginByWxMiniapp: function({
			commit,
			dispatch
		}, code) {
			return new Promise((resolve, reject) => {
				uni.getUserInfo({
					lang: 'zh_CN',
					success(user) {
						auth(user.encryptedData, user.signature, user.rawData, user.iv, code, SHOP_ID, getApp().globalData.spid,
							'wxminiapp').then(res => {
							if (res.error_description) {

							} else {
								commit('setToken', res.access_token);
								commit('setRefreshToken', res.refresh_token);
								dispatch('getUserInfo');
							}
							resolve();
						}).catch(error => {
							reject(error);
						})
					},
					fail(res) {
						reject(res);
					}
				})
			})
		},
		//获取用户信息
		getUserInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getUserInfo().then((res) => {
					commit('setUserInfo', res.data);
					resolve();
				}).catch(err => {
					reject(err);
				})
			})
		},
		//刷新token
		refreshToken({
			state,
			commit
		}) {
			return new Promise((resolve, reject) => {
				auth({
					grant_type: "refresh_token",
					scope: 'all',
					refresh_token: state.refreshToken,
					tenantId: TENANT_ID
				}).then(res => {
					const data = res.data;
					commit('setToken', data.access_token);
					commit('setRefreshToken', data.refresh_token);
					resolve();
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登出
		LogOut({
			commit
		}) {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					commit('setToken', false);
					commit('setUserInfo', {});
					resolve();
				}).catch(error => {
					reject(error)
				})
			})
		},
		//获取当前位置
		getCurrentLocation({
			state,
			commit
		}) {
			return new Promise((resolve, reject) => {
				if (!state.qqmapsdk) {
					state.qqmapsdk = new QQMapWX({
						key: QQMAP_KEY
					});
				}
				uni.getLocation({
					// #ifdef APP-PLUS || MP-WEIXIN
					type: 'gcj02',
					// #endif
					success(loc) {
						state.qqmapsdk.reverseGeocoder({
							location: {
								latitude: loc.latitude,
								longitude: loc.longitude
							},
							success: (res) => {
								let localCity = res.result.address_component.city
								location = {
									localCity: localCity,
									latitude: loc.latitude,
									longitude: loc.longitude,
									isDefault: false
								}
								commit('setCurrentLocation', location);
								resolve();
							},
							fail: (res) => {
								reject(res);
							}
						})
					},
					fail(res) {
						reject(res);
					}
				})
			})
		}
	}
})

export default store
